//解析数组类
function ParseArray() {
  var isArray = function (obj) {
    var arrType = (typeof obj.push + "").toUpperCase();
    if (arrType == "UNDEFINED") {
      return false;
    } else {
      return true;
    }
  };

  var isObject = function (obj) {
    if (!isArray(obj)) {
      var objType = (typeof obj + "").toUpperCase();
      if (objType == "OBJECT") {
        return true;
      }
    }
    return false;
  };

  var isNumber = function (value) {
    var reg = /[0-9]/g;
    return reg.test(value);
  };

  var getTableSql = function (createSql, name) {
    var sql1 = "DROP TABLE IF EXISTS `" + name + "`;\n";
    var sql2 = "CREATE TABLE `" + name + "` (\n";
    var sql3 = "`id` int(11) NOT NULL AUTO_INCREMENT,\n";
    var sql4 = createSql;
    var sql5 = "`remark` varchar(255) DEFAULT NULL,\n";
    var sql6 = "PRIMARY KEY (`id`)\n";
    var sql7 = ") ENGINE=InnoDB DEFAULT CHARSET=utf8;";
    var sql = sql1 + sql2 + sql3 + sql4 + sql5 + sql6 + sql7;
    console.log(sql + "\n");
    return sql;
  };

  //参数:(1)告诉我所有的[属性]名称数组,(2)告诉我你需要哪个[对象]的[属性]字段值,(3)告诉我表的名字
  var getInsertSql = function (allPropsArr, obj, tableName) {
    var insertSql = "";

    allPropsArr.forEach((item, index, arr) => {
      if (!isArray(obj[item])) {
        //【扩展点】这里可以判断数字,然后加入的是数字的字段
        insertSql += obj[item] + ", ";
      } else {
        insertSql += indexArrNum++ + ", ";
      }
    });

    var sql1 = insertSql;
    var sql2 =
      "INSERT INTO `" + tableName + "` VALUES (NULL, " + sql1 + "'暂无备注');";
    console.log(sql2);
    return sql2;
  };

  var isTableCreate = false; //增加一个标记,说明自己已经创建好了当前的表,那就直接走插入语句的流程
  var indexArrNum = 1;
  this.start = function (data, tableName) {
    if (!isArray(data)) {
      return null;
    }
    if (data.length >= 1) {
      console.log("数组长度大于1");
      for (var index = 0; index < data.length; index++) {
        for (var key in data) {
          var allPropsArr = [];
          if (isNumber(key)) {
            //[1].说明是个数组
            //[1].(1)拿到全部的属性值
            if (!isTableCreate) {
              var createSql = "";
              for (var item in data[key]) {
                createSql += "`" + item + "` varchar(255) NOT NULL,\n";
                allPropsArr.push(item);
              }
              getTableSql(createSql, tableName);
              isTableCreate = true;
              //[1].插入新增数据
              getInsertSql(allPropsArr, data[key], tableName);
            } else {
              //[1].插入新增数据
              getInsertSql(allPropsArr, data[key], tableName);
            }
          }
        }
      }
    }
  };
}

export default ParseArray;
